<script setup>
import { ref, onMounted } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import {
  getManagerList,
  updateStatusApi,
  updateManagerInfoApi,
  deleteManagerByIdApi,
  createManagerApi
} from '@/api/manager'
import ChooseImage from '@/components/choose-image.vue'
import ListHeader from '@/components/list-header.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')
//搜索表单数据
const searchform = ref({
  keyword: ''
})

//管理员列表
const roles = ref([])

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getManagerList(currentPage.value, null, searchform.value.keyword)

    tableData.value = res.list.map((item) => {
      item.statusLoading = false
      return item
    })
    total.value = res.totalCount
    roles.value = res.roles
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除公告
const onDelete = async (row) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteManagerByIdApi(row.id)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('删除失败', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
  console.log(row)
}

//新增管理员
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增管理员'
  fromDrawerRef.value.open()
  form.value = {
    username: '',
    password: '',
    role_id: null,
    status: 1,
    id: null,
    avatar: ''
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  username: '',
  password: '',
  role_id: null,
  status: 1,
  avatar: '',
  id: null
})

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()
  if (changId.value !== 0) {
    try {
      await updateManagerInfoApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('编辑失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await createManagerApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改管理员信息
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改管理员信息'
  const { username, password, role_id, status, avatar, id } = row
  form.value = {
    username,
    password,
    role_id,
    status,
    avatar,
    id
  }
  changId.value = id
  fromDrawerRef.value.open()
}

//重置
const onResetSearch = () => {
  searchform.value.keyword = ''
  getData()
}

//修改状态
const onChangeStatus = async (status, row) => {
  row.statusLoading = true
  try {
    await updateStatusApi(row.id, status)
    toast('修改状态成功')
    row.status = status
  } catch (error) {
  } finally {
    row.statusLoading = false
  }
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <!-- 搜索 -->
    <el-form :model="searchform" label-width="80px" class="mb-3" size="small">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="关键词">
            <el-input v-model="searchform.keyword" placeholder="管理层昵称" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="8">
          <div class="flex items-center justify-end">
            <el-button type="primary" @click="getData">搜索</el-button>
            <el-button @click="onResetSearch">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <ListHeader @create="onAdd" @refresh="getData"></ListHeader>
  </el-card>
  <el-table :data="tableData" stripe style="width: 100%">
    <el-table-column label="管理员" width="200">
      <template #default="{ row }">
        <div class="flex items-center">
          <el-avatar :size="40" :src="row.avatar">
            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
          </el-avatar>
          <div class="ml-3">
            <h6>{{ row.username }}</h6>
            <small>ID:{{ row.id }}</small>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="create_time" label="所属管理员" align="center">
      <template #default="{ row }">
        {{ row.role?.name || '-' }}
      </template>
    </el-table-column>
    <el-table-column prop="content" label="状态" width="120">
      <template #default="{ row }">
        <el-switch
          v-model="row.status"
          :active-value="1"
          :inactive-value="0"
          @change="onChangeStatus($event, row)"
          :loading="row.statusLoading"
          :disabled="row.super == 1"
        >
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180" align="center">
      <template #default="scoped">
        <small v-if="scoped.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
        <div v-else>
          <el-button type="primary" size="small" text @click="onChange(scoped.row)">修改</el-button>
          <el-popconfirm
            title="是否要删除该管理员？"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="onDelete(scoped.row)"
          >
            <template #reference>
              <el-button type="primary" size="small" text>删除</el-button>
            </template>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex justify-center justify-center mt-5">
    <el-pagination
      @current-change="getData"
      :current-page="currentPage"
      background
      layout="prev,pager,next"
      :total="total"
    />
  </div>
  <FromDrawer ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" label-width="80px" :inline="false">
      <el-form-item label="用户名">
        <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <ChooseImage v-model:url="form.avatar"></ChooseImage>
      </el-form-item>
      <el-form-item label="所属角色">
        <el-select v-model="form.role_id" placeholder="选中所属角色">
          <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"> </el-switch>
      </el-form-item>
    </el-form>
  </FromDrawer>
</template>

<style scoped></style>
